package x.ovo.wechat.bot.plugin;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@UtilityClass
public class LogUtil {

    private static final String PACKAGE = "x.ovo.wechat.bot";
    private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    public static String printError(Throwable e) {

        if (Objects.isNull(e)) return null;


        StringBuilder sb = new StringBuilder();
        sb.append("\n");
        sb.append("=============================== 异常开始 ===============================\n");
        sb.append("\t信息: ").append(e.getMessage()).append("\n");
        sb.append("\t时间: ").append(SDF.format(new Date())).append("\n");
        sb.append("\t类型: ").append(e.getClass()).append("\n");
        if (e.getCause() != null) {
            sb.append("\t原因: ").append(e.getCause().getMessage()).append("\n");
        }
        for (StackTraceElement element : e.getStackTrace()) {
            if (element.getClassName().startsWith(PACKAGE)) {
                sb.append("\t位置: ").append(element.toString().replace("x.ovo.wechat.bot.impl.", "")).append("\n");
                break;
            }
        }
        String s = Arrays.stream(e.getStackTrace()).map(StackTraceElement::toString).collect(Collectors.joining("\n\t\t\t\t\t\t\t\t\t⬆️\n\t\t"));
        sb.append("\n\t堆栈: \n").append("\t\t").append(s).append("\n");
        sb.append("=============================== 异常结束 ===============================\n");

        log.error(sb.toString());

        return sb.toString();
    }

}
